package com.examination.mlib.db;

import static com.yilijk.base.utils.ALog.isEnableLog;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;

import androidx.annotation.Nullable;

import com.examination.mlib.constants.UserInfoConstants;
import com.yilijk.base.utils.ALog;
import com.yilijk.base.utils.SharedPreferencesUtils;

public class DataBaseUtil {
    private static DataBaseUtil util;

    private DataBaseUtil() {
    }

    public static DataBaseUtil getInstance() {
        if (util == null) {
            synchronized (DataBaseUtil.class) {
                if (util == null) {
                    util = new DataBaseUtil();
                }
            }
        }
        return util;
    }

    public boolean updateData(Context context, String fileName, String dbData) {

        String userId = SharedPreferencesUtils.getInstance().getString(UserInfoConstants.account_id, "");
        if (TextUtils.isEmpty(userId)) {
            return false;
        }

        return updateData(context, fileName, dbData, userId);

    }

    public boolean updateData(Context context, String fileName, String dbData, String nameKey) {

        if (TextUtils.isEmpty(dbData) || TextUtils.isEmpty(fileName) || TextUtils.isEmpty(nameKey)) {
            return false;
        }

        fileName = "ylP_" + fileName;
        DBOpenHelper helper = DBOpenHelper.getInstance(context);
        SQLiteDatabase database = helper.getWritableDatabase();
        Cursor cursor = null;
        database.beginTransaction();
        try {
            database.execSQL("CREATE TABLE IF NOT EXISTS " + fileName + " (_id TEXT PRIMARY KEY,data TEXT)");
            cursor = database.query(fileName, new String[]{"data"}, "_id=?", new String[]{nameKey + ""}, null, null, null);
            if (cursor == null) {
                return false;
            }
            int count = cursor.getCount();
            ALog.e("oakkkdb", "count: " + count);
            if (count > 0) {
                ContentValues values = new ContentValues();
                values.put("data", dbData);
                database.update(fileName, values, "_id=?", new String[]{nameKey + ""});
            } else {
                ContentValues values = new ContentValues();
                values.put("_id", nameKey + "");
                values.put("data", dbData);
                database.insert(fileName, null, values);
            }
            if (isEnableLog) {
                getAllDb(database, fileName);
            }
            database.setTransactionSuccessful();
        } catch (Throwable throwable) {
            return false;
        } finally {
            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
            }
            database.endTransaction();
            helper.close();
        }
        return true;
    }

    public boolean setData(Context context, String fileName, String dbData) {
        String userId = SharedPreferencesUtils.getInstance().getString(UserInfoConstants.account_id, "");
        if (TextUtils.isEmpty(userId)) {
            return false;
        }

        return setData(context, fileName, dbData, userId);

    }

    public boolean setData(Context context, String fileName, String dbData, String nameKey) {

        if (TextUtils.isEmpty(dbData) || TextUtils.isEmpty(fileName) || TextUtils.isEmpty(nameKey)) {
            return false;
        }

        fileName = "ylP_" + fileName;
        DBOpenHelper helper = DBOpenHelper.getInstance(context);
        SQLiteDatabase database = helper.getWritableDatabase();
        Cursor cursor = null;
        database.beginTransaction();
        try {
            database.execSQL("CREATE TABLE IF NOT EXISTS " + fileName + " (_id TEXT PRIMARY KEY,data TEXT)");
            cursor = database.query(fileName, new String[]{"data"}, "_id=?", new String[]{nameKey + ""}, null, null, null);
            if (cursor == null) {
                return false;
            }
            int count = cursor.getCount();
            ALog.e("oakkkdb", "count: " + count);
            if (count > 0) {
                ContentValues values = new ContentValues();
                values.put("data", dbData);
                database.update(fileName, values, "_id=?", new String[]{nameKey + ""});
            } else {
                ContentValues values = new ContentValues();
                values.put("_id", nameKey + "");
                values.put("data", dbData);
                database.insert(fileName, null, values);
            }
            if (isEnableLog) {
                getAllDb(database, fileName);
            }
            database.setTransactionSuccessful();
        } catch (Throwable throwable) {
            return false;
        } finally {
            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
            }
            database.endTransaction();
            helper.close();
        }
        return true;
    }

    public String getData(Context context, String fileName) {
        String userId = SharedPreferencesUtils.getInstance().getString(UserInfoConstants.account_id, "");
        if (TextUtils.isEmpty(userId)) {
            return null;
        }

        return getData(context, fileName, userId);

    }

    @Nullable
    public String getData(Context context, String fileName, String nameKey) {
        if (TextUtils.isEmpty(fileName) || TextUtils.isEmpty(nameKey)) {
            return null;
        }
        fileName = "ylP_" + fileName;
        DBOpenHelper helper = DBOpenHelper.getInstance(context);
        SQLiteDatabase database = helper.getWritableDatabase();
        Cursor cursor = null;
        database.beginTransaction();
        String result = null;
        try {
            database.execSQL("CREATE TABLE IF NOT EXISTS " + fileName + " (_id TEXT PRIMARY KEY,data TEXT)");

            cursor = database.query(fileName, new String[]{"data"}, "_id=?", new String[]{nameKey + ""}, null, null, null);
            if (cursor != null && cursor.moveToFirst()) {

                int dataIndex = cursor.getColumnIndex("data");
                ALog.e("oakkkdb", "dataIndex: " + dataIndex);
                if (dataIndex >= 0) {
                    result = cursor.getString(dataIndex);
                }

            } else {
                return null;
            }


            if (isEnableLog) {
                getAllDb(database, fileName);
            }
            database.setTransactionSuccessful();
        } catch (Throwable throwable) {
            return null;
        } finally {
            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
            }
            database.endTransaction();
            helper.close();
        }
        return result;
    }

    public boolean removeData(Context context, String fileName) {
        String userId = SharedPreferencesUtils.getInstance().getString(UserInfoConstants.account_id, "");
        if (TextUtils.isEmpty(userId)) {
            return false;
        }

        return removeData(context, fileName, userId);

    }

    public boolean removeData(Context context, String fileName, String nameKey) {
        if (TextUtils.isEmpty(fileName) || TextUtils.isEmpty(nameKey)) {
            return false;
        }
        fileName = "ylP_" + fileName;
        DBOpenHelper helper = DBOpenHelper.getInstance(context);
        SQLiteDatabase database = helper.getWritableDatabase();
        Cursor cursor = null;
        database.beginTransaction();

        try {
            database.execSQL("CREATE TABLE IF NOT EXISTS " + fileName + " (_id TEXT PRIMARY KEY,data TEXT)");

            database.delete(fileName, "_id=?", new String[]{nameKey + ""});

            if (isEnableLog) {
                getAllDb(database, fileName);
            }
            database.setTransactionSuccessful();
        } catch (Throwable throwable) {
            return false;
        } finally {
            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
            }
            database.endTransaction();
            helper.close();
        }
        return true;
    }

    private void getAllDb(SQLiteDatabase database, String fileName) throws Throwable {
        Cursor cursor = null;
        try {
            cursor = database.query(fileName, null, null, null, null, null, null);
            if (cursor.moveToFirst()) {
                do {
                    int userIdIndex = cursor.getColumnIndex("_id");
                    int dataIndex = cursor.getColumnIndex("data");
                    String userId = cursor.getString(userIdIndex);
                    String data = cursor.getString(dataIndex);
                    ALog.e("oakkkdb", "query all: " + userId + " ==> " + data);
                } while (cursor.moveToNext());
            }
        } catch (Throwable throwable) {

        } finally {
            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
            }
        }
    }
}
